<template>
  <div class="app-container">
    <!-- 装饰元素 -->
    <div class="decoration leaf-1">
      <i class="fas fa-leaf"></i>
    </div>
    <div class="decoration leaf-2">
      <i class="fas fa-leaf"></i>
    </div>

    <!-- 导航栏 -->
    <div class="nav-bar">
      <div class="back-btn" @click="handleBack">
        <i class="fas fa-arrow-left"></i>
      </div>
      <div>完善个人信息</div>
    </div>

    <!-- 内容区域 -->
    <div class="content-container">
      <!-- 表单区域 -->
      <div class="form-container fade-in">
        <div class="form-title">
          <i class="fas fa-user-edit"></i>
          个人信息收集
        </div>

        <div class="form-description">
          为了给您提供更好的服务，请完善以下个人信息
        </div>

        <form @submit.prevent="handleSubmit">
          <div class="form-group">
            <label class="form-label" for="name">姓名</label>
            <input
              type="text"
              id="name"
              class="form-input"
              placeholder="请输入您的姓名"
              v-model="formData.name"
              required
            />
          </div>

          <div class="form-group">
            <label class="form-label">性别</label>
            <div class="radio-group">
              <label class="radio-option">
                <input
                  type="radio"
                  name="gender"
                  value="M"
                  class="radio-input"
                  v-model="formData.gender"
                  required
                />
                <span class="radio-custom"></span>
                <span>男</span>
              </label>
              <label class="radio-option">
                <input
                  type="radio"
                  name="gender"
                  value="F"
                  class="radio-input"
                  v-model="formData.gender"
                />
                <span class="radio-custom"></span>
                <span>女</span>
              </label>
            </div>
          </div>

          <div class="form-group">
            <label class="form-label" for="employeeId">工号（如有）</label>
            <input
              type="text"
              id="employeeId"
              class="form-input"
              placeholder="请输入您的工号（选填）"
              v-model="formData.employeeId"
            />
          </div>

          <div class="form-group">
            <label class="form-label" for="company">公司名称</label>
            <input
              type="text"
              id="company"
              class="form-input"
              placeholder="请输入您所在的公司"
              v-model="formData.company"
              required
            />
          </div>

          <div class="form-group">
            <label class="form-label" for="birthdate">出生年月日</label>
            <input
              type="date"
              id="birthdate"
              class="form-input"
              v-model="formData.birthdate"
              :max="maxDate"
              required
            />
          </div>

          <button type="submit" class="submit-btn" :disabled="loading">
            {{ loading ? "提交中..." : "提交信息" }}
          </button>
        </form>
      </div>
    </div>
  </div>
</template>

<script>
import { updateUserById, getZdmemberUserByID } from "../../api/index";

export default {
  name: "UserInfoForm",
  data() {
    return {
      formData: {
        name: "",
        gender: "",
        employeeId: "",
        company: "",
        birthdate: "",
      },
      maxDate: new Date().toISOString().split("T")[0],
      loading: false,
      currentUser: null,
    };
  },
  created() {
    // 获取当前用户信息，填充表单
    this.getCurrentUserInfo();
  },
  methods: {
    // 获取当前用户信息
    getCurrentUserInfo() {
      try {
        // 从localStorage获取用户信息
        const userInfoStr = localStorage.getItem("userinfo");
        if (userInfoStr) {
          this.currentUser = JSON.parse(userInfoStr);
          console.log("获取到的用户信息:", this.currentUser);

          // 填充表单数据，处理null值
          this.formData = {
            name: this.currentUser.name || "",
            gender: this.currentUser.gender || "",
            employeeId: this.currentUser.memberno || "",
            company: this.currentUser.company || "",
            birthdate: this.currentUser.birthday
              ? this.formatDateForInput(this.currentUser.birthday)
              : "",
          };
        } else {
          console.warn("未找到用户信息");
        }
      } catch (error) {
        console.error("获取用户信息失败:", error);
      }
    },

    // 将日期格式转换为 input[type="date"] 需要的格式 (YYYY-MM-DD)
    formatDateForInput(dateString) {
      if (!dateString) return "";
      try {
        const date = new Date(dateString);
        if (isNaN(date.getTime())) {
          return "";
        }
        return date.toISOString().split("T")[0];
      } catch (error) {
        console.error("日期格式转换错误:", error);
        return "";
      }
    },

    // 构建接口需要的参数格式
    buildApiParams() {
      if (!this.currentUser) {
        throw new Error("用户信息不存在");
      }

      return {
        id: this.currentUser.id, // 用户ID
        name: this.formData.name,
        gender: this.formData.gender || null,
        company: this.formData.company,
        birthday: this.formData.birthdate || null,
        memberno: this.formData.employeeId || null,
        manager: this.currentUser.manager || false,
        unitId: this.currentUser.unitId,
      };
    },

    async handleSubmit() {
      // 验证表单
      if (
        !this.formData.name ||
        !this.formData.gender ||
        !this.formData.company ||
        !this.formData.birthdate
      ) {
        alert("请填写所有必填字段");
        return;
      }

      this.loading = true;

      try {
        // 构建接口参数
        const apiParams = this.buildApiParams();

        console.log("提交的用户信息:", apiParams);

        // 调用修改用户信息接口
        const response = await updateUserById(apiParams);

        console.log("接口响应:", response);

        // 根据实际接口返回结构判断成功与否
        // 这里假设接口返回包含 success 字段或直接返回更新后的用户数据
        if (response.code == 200) {
          alert("个人信息提交成功！");
          this.loading = false;

          // 更新本地存储的用户信息
          this.getZdmemberUserByID();
        } else {
          alert("提交失败，请重试");
        }
      } catch (error) {}
    },

    // 更新本地存储的用户信息
    getZdmemberUserByID() {
      let data = {
        id: localStorage.getItem("userId"),
      };
      getZdmemberUserByID(data).then((res) => {
        if (res.code === 200) {
          localStorage.setItem("unitId", res.data.unitId);
          localStorage.setItem("userinfo", JSON.stringify(res.data));
        } else {
          this.$toast?.("获取用户信息失败");
        }
      });
    },

    handleBack() {
      // 返回上一页
      this.$router.go(-1);
    },
  },
};
</script>

<style scoped>
/* 保持原有的样式不变 */
.app-container {
  max-width: 414px;
  margin: 0 auto;
  background: linear-gradient(to bottom, #f8f7fc, #f0edf9);
  min-height: 100vh;
  position: relative;
  overflow-x: hidden;
}

/* 导航栏 */
.nav-bar {
  height: 50px;
  background-color: rgba(255, 255, 255, 0.9);
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 17px;
  font-weight: 600;
  color: #333;
  border-bottom: 1px solid rgba(142, 124, 195, 0.1);
  position: relative;
}

.back-btn {
  position: absolute;
  left: 15px;
  font-size: 20px;
  color: #8e7cc3;
  cursor: pointer;
}

/* 内容区域 */
.content-container {
  padding: 25px 20px;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

/* 表单样式 */
.form-container {
  background-color: white;
  border-radius: 16px;
  padding: 25px;
  box-shadow: 0 4px 12px rgba(142, 124, 195, 0.1);
  max-width: 90%;
}

.form-title {
  font-size: 18px;
  font-weight: 600;
  margin-bottom: 8px;
  color: #333;
  display: flex;
  align-items: center;
  justify-content: center;
}

.form-title i {
  margin-right: 8px;
  color: #8e7cc3;
}

.form-description {
  font-size: 13px;
  color: #666;
  text-align: center;
  margin-bottom: 25px;
  line-height: 1.5;
}

.form-group {
  margin-bottom: 20px;
}

.form-label {
  display: block;
  margin-bottom: 8px;
  font-size: 14px;
  font-weight: 500;
  color: #555;
}

.form-input {
  width: 90%;
  padding: 14px 16px;
  border: 1.5px solid #e8e3f5;
  border-radius: 12px;
  font-size: 15px;
  outline: none;
  transition: all 0.3s ease;
  background-color: #faf9ff;
}

.form-input:focus {
  border-color: #8e7cc3;
  background-color: #fff;
  box-shadow: 0 0 0 3px rgba(142, 124, 195, 0.1);
}

.radio-group {
  display: flex;
  gap: 20px;
}

.radio-option {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.radio-input {
  display: none;
}

.radio-custom {
  width: 20px;
  height: 20px;
  border-radius: 50%;
  border: 2px solid #d0c9e6;
  margin-right: 8px;
  position: relative;
  transition: all 0.3s ease;
}

.radio-input:checked + .radio-custom {
  border-color: #8e7cc3;
  background-color: #8e7cc3;
}

.radio-input:checked + .radio-custom::after {
  content: "";
  position: absolute;
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background-color: white;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.submit-btn {
  width: 100%;
  padding: 16px;
  background: linear-gradient(135deg, #8e7cc3, #a293d2);
  color: white;
  border: none;
  border-radius: 12px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  margin-top: 10px;
  box-shadow: 0 4px 10px rgba(142, 124, 195, 0.3);
}

.submit-btn:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 6px 15px rgba(142, 124, 195, 0.4);
}

.submit-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
}

/* 装饰元素 */
.decoration {
  position: absolute;
  z-index: 0;
  opacity: 0.05;
}

.leaf-1 {
  top: 15%;
  left: 5%;
  transform: rotate(45deg);
  font-size: 60px;
  color: #8e7cc3;
}

.leaf-2 {
  bottom: 25%;
  right: 5%;
  transform: rotate(-20deg);
  font-size: 50px;
  color: #8e7cc3;
}

/* 动画效果 */
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.fade-in {
  animation: fadeIn 0.4s ease forwards;
}
</style>
